import copy

xrl = lambda l: xrange(len(l))

def add_pattern(patterns, size, alphabet):
    result = [[]]
    for s in xrange(size):
        new_res = []
        for a in alphabet:
            for r in result:
                new_res.append(r + [a])
        result = new_res

    patterns[size] = result

def layer_gen(nets, postlayer, prelayer, alphabet, patterns):
    prelayer += 1

    if not prelayer in patterns:
        add_pattern(patterns, prelayer, alphabet)

    for n in xrange(postlayer):
        newnets = []
        for pat in patterns[prelayer]:
            for net in nets:
                newnet = copy.deepcopy(net)
                newnet[-1].append(pat)
                newnets.append(newnet)

        nets = newnets

    return newnets

def generate(layers, alphabet):
    nets = [[]]
    patterns = {}

    for l in xrange(1,len(layers)):
        for net in nets:
            net.append([]) # next layer

        nets = layer_gen(nets, layers[l], layers[l-1], alphabet, patterns)

    return nets
